package com.feilong.mscv5plus;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.UnsupportedEncodingException;

import tp.xmaihh.serialport.SerialHelper;
import tp.xmaihh.serialport.bean.ComBean;

/**
 * @ClassName: SerialPortUtils
 * @Description: java类作用描述
 * @Author: potato
 * @CreateDate: 2022/10/17 10:20
 * @UpdateUser: potato
 * @UpdateDate: 2022/10/17 10:20
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class SerialPortUtils {

    private SerialHelper serialHelper;
    private StringBuilder result = new StringBuilder();
    public SerialPortUtils(){
        serialHelper = new SerialHelper("dev/ttyS5", 115200) {
            @Override
            protected void onDataReceived(ComBean paramComBean) {
                byte[] bRec = paramComBean.bRec;
                try {
                    String res = new String(bRec,"utf-8");
                    Log.d("onDataReceived", "onDataReceived: "+res);
                    Log.d("onDataReceived", "len: "+res.length());
                    result.append(res);
                    handler.removeMessages(0);
                    handler.sendEmptyMessageDelayed(0,100);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        };
        try {
            serialHelper.open();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(null!=onPortReceived){
                onPortReceived.onReceived(result.toString());
            }
        }
    };
    public void send(String text){
        result.delete(0,result.length());
        Log.d("onDataReceived", "send: "+result.toString());
        serialHelper.sendTxt(text);
    }
    public void clear(){
        result.delete(0,result.length());
    }
    public boolean isOpen(){
        return serialHelper.isOpen();
    }
    public void close(){
        serialHelper.close();
    }
    public interface OnPortReceived{
        void onReceived(String text);
    }
    public OnPortReceived onPortReceived;
    public void setOnPortReceived(OnPortReceived onPortReceived){
        this.onPortReceived = onPortReceived;
    }
}
